package com.xyz.keshe.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.xyz.keshe.R;
import com.xyz.keshe.model.Announcement;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

public class AnnouncementManageAdapter extends BaseAdapter {

    private Context context;
    private List<Announcement> announcements;
    private OnAnnouncementActionListener listener;

    public interface OnAnnouncementActionListener {
        void onEdit(Announcement announcement);
        void onDelete(Announcement announcement);
    }

    public AnnouncementManageAdapter(Context context, List<Announcement> announcements, OnAnnouncementActionListener listener) {
        this.context = context;
        this.announcements = announcements;
        this.listener = listener;
    }

    @Override
    public int getCount() {
        return announcements.size();
    }

    @Override
    public Object getItem(int position) {
        return announcements.get(position);
    }

    @Override
    public long getItemId(int position) {
        return announcements.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_announcement_manage, parent, false);
        }

        Announcement announcement = announcements.get(position);

        TextView tvTitle = convertView.findViewById(R.id.tv_announcement_title);
        TextView tvContent = convertView.findViewById(R.id.tv_announcement_content);
        TextView tvTime = convertView.findViewById(R.id.tv_announcement_time);
        Button btnEdit = convertView.findViewById(R.id.btn_edit_announcement);
        Button btnDelete = convertView.findViewById(R.id.btn_delete_announcement);

        tvTitle.setText(announcement.getTitle());
        
        // 限制内容显示长度
        String content = announcement.getContent();
        if (content.length() > 50) {
            content = content.substring(0, 50) + "...";
        }
        tvContent.setText(content);

        // 格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        tvTime.setText(sdf.format(announcement.getCreateTimeAsDate()));

        btnEdit.setOnClickListener(v -> {
            if (listener != null) {
                listener.onEdit(announcement);
            }
        });

        btnDelete.setOnClickListener(v -> {
            if (listener != null) {
                listener.onDelete(announcement);
            }
        });

        return convertView;
    }
} 